//
//  XPCustomTabBar.swift
//  SinaWeibo
//
//  Created by 徐攀 on 16/5/11.
//  Copyright © 2016年 徐攀. All rights reserved.
//

import UIKit
/** 协议 */
protocol XPCustomTabBarDelegate: NSObjectProtocol {
    func didClickComposeButton()
}

class XPCustomTabBar: UITabBar {
    
    var callBackClosure: (()->())?
    
    weak var composeBtnDelegate: XPCustomTabBarDelegate?

    // MARK: - 懒加载撰写按钮
    lazy var composeBtn: UIButton = {
        let button = UIButton()
        //点击事件
        button.addTarget(self, action: #selector(XPCustomTabBar.composeBtnClick), forControlEvents: .TouchUpInside)
        //图片背景
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        //大小
        button.sizeToFit()
        
        return button
    }()
    
    private func setupUI() {
        addSubview(composeBtn)
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
// MARK: - 子控件的frame
extension XPCustomTabBar {
    override func layoutSubviews() {
        super.layoutSubviews()
        
        composeBtn.center = CGPoint(x: bounds.size.width / 2, y: bounds.size.height / 2)
        var index = 0
        for childView in subviews {
            if childView.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                
                childView.bounds.size = CGSize(width: bounds.size.width / 5, height: bounds.size.height)
                childView.frame.origin.x = CGFloat(index) * childView.bounds.size.width
                index += 1
                if index == 2 { index += 1 }
            }
        }
    }
}
// MARK: - 撰写按钮的点击事件
extension XPCustomTabBar {
   @objc private func composeBtnClick() {
        callBackClosure?()
        composeBtnDelegate?.didClickComposeButton()
    }
}
